from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyEditModelForm, PrettyModelForm, UserModelFrom
def pretty_list(request):
    """靓号列表"""
    # 实验数据
    # for i in range(300):
    #     if i < 10:
    #         models.PrettyNum.objects.create(
    #             mobile=f'1771233597{i}',
    #             price=1+i,
    #             level=3,
    #             status=1
    #         )
    #     elif i > 10 and i < 100:
    #         models.PrettyNum.objects.create(
    #             mobile=f'177123359{i}',
    #             price=1 + i,
    #             level=2,
    #             status=1
    #         )
    #     else:
    #         models.PrettyNum.objects.create(
    #             mobile=f'17712335{i}',
    #             price=1 + i,
    #             level=2,
    #             status=2
    #         )
    # 搜索
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['mobile__contains'] = search_data

    # res = models.PrettyNum.objects.filter(**data_dict)
    # 1，从数据库中拿到所欲数据
    #   .order_by("-level") 排序 加上减号表示倒序
    # queryset = models.PrettyNum.objects.all().order_by("-level")

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request, queryset)

    page_queryset = page_object.page_queryset
    page_string = page_object.html()

    context = {
        'search_data': search_data,

        "queryset": page_queryset,  # 分完页的数据
        'page_string': page_string  # 生成的页码
    }

    # 把数据传到html页面
    return render(request, 'pretty_list.html', context)

    # 根据用户想访问的页数 算出起始和结束
    # page = int(request.GET.get('page', 1))
    # page_size = 10
    # start = (page - 1) * page_size
    # end = page * page_size
    # queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start: end]
    #
    # # 数据总条数
    # total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
    # # 总页码
    # total_page_count, div = divmod(total_count, page_size)  # (除数，被除数) 得（商，余数）
    # if div:  # 判断余数是否大于1 大于1 页码数加1
    #     total_page_count += 1

    # # 计算出应该显示的页码【当前页的前后五页
    # plus = 5
    #
    # # 判断数据库中的数据比较少的时候 没有到达11页那就不同
    # if total_page_count <= 2 * plus + 1:
    #     start_page = 1
    #     end_page = total_page_count
    # else:
    #     # 数据库中的数据超过11页
    #     # 当前页数大于5时（小的极值）
    #     if page <= plus:
    #         start_page = 1
    #         end_page = 2 * plus + 1
    #     else:
    #         # 当后页数超过总页数时
    #         if (page + plus) > total_page_count:
    #             start_page = total_page_count - 2 * plus
    #             end_page = total_page_count
    #         else:
    #             start_page = page - plus
    #             end_page = page + plus
    #
    #     # 我写的垃圾逻辑
    #     # start_page = page - plus
    #     # if start_page <= 0:
    #     #     start_page = 1
    #     # end_page = page + plus
    #     # if end_page >= total_page_count:
    #     #     end_page = total_page_count + 1
    #
    # # 页码
    # page_str_list = []
    #
    # page_str_list.append('<li><a href="/pretty/list/?page=1">首页</a></li>')
    #
    # # 上一页
    # if page > 1:
    #     prev = '<li><a href="/pretty/list/?page={}">«</a></li>'.format(page - 1)
    # else:
    #     prev = '<li><a href="/pretty/list/?page={}">«</a></li>'.format(1)
    # page_str_list.append(prev)
    # # le = len(models.PrettyNum.objects.all())
    # # for i in range(1, le // 10 + 2):
    # # 列表页面（数字）
    # for i in range(start_page, end_page + 1):
    #     # 给当前页加上标志
    #     if i == page:
    #         ele = '<li class="active"><a href="/pretty/list/?page={}">{}</a></li>'.format(i, i)
    #     else:
    #         ele = '<li><a href="/pretty/list/?page={}">{}</a></li>'.format(i, i)
    #     page_str_list.append(ele)
    #
    # # 下一页
    # if page < total_page_count:
    #     prev = '<li><a href="/pretty/list/?page={}">»</a></li>'.format(page + 1)
    # else:
    #     prev = '<li><a href="/pretty/list/?page={}">»</a></li>'.format(total_page_count)
    # page_str_list.append(prev)
    #
    # # 尾页
    # page_str_list.append('<li><a href="/pretty/list/?page={}">尾页</a></li>'.format(total_page_count))
    #
    # # 输入页码
    # search_string = """
    #         <li style="float: right">
    #             <form class="form-inline" method="get">
    #                 <div class="form-group">
    #                     <input style="width: 80px" type="text" name="page" class="form-control" id="exampleInputEmail3"
    #                            placeholder="输入页码">
    #                 </div>
    #                 <button type="submit" class="btn btn-default">
    #                     <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
    #                 </button>
    #             </form>
    #         </li>
    # """
    # page_str_list.append(search_string)
    # page_string = mark_safe("".join(page_str_list))

    # 把数据传到html页面
    # return render(request, 'pretty_list.html', {
    #     "queryset": page_queryset,
    #     'search_data': search_data,
    #     'page_string': page_string
    # })


def pretty_add(request):
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {'form': form})

    # 提交post
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()  # 保存
        return redirect('/pretty/list/')
    # 检验失败 在页面显示错误信息
    # print(form.errors)  # 校验失败的到所有的错误信息
    else:
        return render(request, 'pretty_add.html', {'form': form})


def pretty_edit(request, nid):
    """编辑靓号"""
    # 1 通过id拿到对象
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == 'GET':
        # 根据id去数据库获取要编辑的数据(对象)
        # row_object = models.UserInfo.objects.filter(id=nid).first()
        # instance=row_object 加上这个modelform会把默认值显示在输入框
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})

    # post
    # row_object = models.UserInfo.objects.filter(id=nid).first() # 拿到对应的行 对象
    form = PrettyModelForm(data=request.POST, instance=row_object)  # instance=rew_object 没有就是添加，写了就是更新
    if form.is_valid():
        # 默认保存的是用户输入的数据
        # 如果有些不是用户输入的数据，也要保存到数据库 【model = models.UserInfo 规定的表中
        # form.instance.数据表字段名 = 某个想要保存的数据
        form.save()
        return redirect('/pretty/list/')
    # 否则回到有错误提示的页面
    return render(request, 'user_edit.html', {"form": form})


def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')